package howl.Servlets;

import howl.model.Handler;
import howl.model.Model;
import howl.types.HowlUser;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.jdo.Query;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import compiler.HowlCompiler;
import compiler.HowlToken;
import compiler.exceptions.HowlModelException;
import compiler.exceptions.HowlParserException;
import compiler.exceptions.HowlUnauthorisedAction;

@SuppressWarnings("serial")
public class HowlCommandServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		System.out.println(req);
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		String com = req.getParameter("command");

	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		System.out.println(req);
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		HowlUser hu = Model.getHowlUserfromUser(user);
		String com = req.getParameter("command");
		HowlCompiler compiler = new HowlCompiler();
		try {
			List<HowlToken> ht = compiler.parse(com);
			Handler h = new Handler(hu);
			for (HowlToken t : ht) {
				h.Handle(t);
			}
			resp.sendRedirect("/Auth/index.jsp");

		} catch (HowlParserException e) {
			resp.sendRedirect("/Auth/QuickEntry.jsp?Action=FAILED&msg="+ e.getMessage());
		} catch (HowlModelException e1) {
			resp.sendRedirect("/Auth/QuickEntry.jsp?Action=FAILED&msg="+ e1.getMsg());
		} catch(HowlUnauthorisedAction e2) {
			resp.sendRedirect("/Auth/QuickEntry.jsp?Action=FAILED&msg="+ e2.getMessage());
		}
	}

}
